<template>
  <div class="projects-page">
    <div class="page-header">
      <div class="header-left">
        <h1>项目管理</h1>
        <p>管理您的所有项目</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="showCreateDialog = true">
          <el-icon><Plus /></el-icon>
          新建项目
        </el-button>
      </div>
    </div>
    
    <!-- 搜索和筛选 -->
    <el-card class="filter-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="项目名称">
          <el-input
            v-model="searchForm.keyWord"
            placeholder="请输入项目名称"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="项目状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="全部" :value="undefined" />
            <el-option label="进行中" :value="0" />
            <el-option label="已完成" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 项目列表 -->
    <el-card class="project-list-card">
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      
      <div v-else-if="projects.length === 0" class="empty-state">
        <el-empty description="暂无项目数据">
          <el-button type="primary" @click="showCreateDialog = true">
            创建第一个项目
          </el-button>
        </el-empty>
      </div>
      
      <div v-else class="project-grid">
        <div
          v-for="project in projects"
          :key="project.id"
          class="project-card"
          @click="goToProject(project)"
        >
          <div class="project-header">
            <h3>{{ project.name }}</h3>
            <el-dropdown @command="(command) => handleProjectAction(command, project)">
              <el-button type="text" @click.stop>
                <el-icon><MoreFilled /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="view">查看详情</el-dropdown-item>
                  <el-dropdown-item command="board">看板视图</el-dropdown-item>
                  <el-dropdown-item command="members">成员管理</el-dropdown-item>
                  <el-dropdown-item command="edit" divided>编辑项目</el-dropdown-item>
                  <el-dropdown-item command="delete" class="danger">删除项目</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
          
          <div class="project-content">
            <p class="description">{{ project.description || '暂无描述' }}</p>
            
            <div class="project-meta">
              <div class="meta-item">
                <el-icon><Calendar /></el-icon>
                <span>{{ formatDate(project.startDate) }} - {{ formatDate(project.endDate) }}</span>
              </div>
              <div class="meta-item">
                <el-icon><User /></el-icon>
                <span>{{ project.members?.length || 0 }} 名成员</span>
              </div>
            </div>
            
            <div class="project-status">
              <el-tag :type="getStatusType(project.status)">
                {{ getStatusText(project.status) }}
              </el-tag>
              <span class="create-time">{{ formatDate(project.createdAt) }}</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div v-if="totalCount > 0" class="pagination-container">
        <el-pagination
          :current-page="pagination.pageIndex"
          :page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalCount"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 创建/编辑项目对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editingProject ? '编辑项目' : '新建项目'"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="projectFormRef"
        :model="projectForm"
        :rules="projectRules"
        label-width="80px"
      >
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="projectForm.name" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="项目描述" prop="description">
          <el-input
            v-model="projectForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入项目描述"
          />
        </el-form-item>
        <el-form-item label="开始日期">
          <el-date-picker
            v-model="projectForm.startDate"
            type="date"
            placeholder="选择开始日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker
            v-model="projectForm.endDate"
            type="date"
            placeholder="选择结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          {{ submitting ? '保存中...' : '保存' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { getProjectList, createProject, updateProject, deleteProject, type Project, type CreateProjectRequest, type UpdateProjectRequest } from '@/api/project'
import dayjs from 'dayjs'

const router = useRouter()

const loading = ref(false)
const submitting = ref(false)
const showCreateDialog = ref(false)
const editingProject = ref<Project | null>(null)
const projects = ref<Project[]>([])
const totalCount = ref(0)

const searchForm = reactive({
  keyWord: '',
  status: undefined as number | undefined
})

const dateRange = ref<[string, string] | null>(null)

const pagination = reactive({
  pageIndex: 1,
  pageSize: 12
})

const projectFormRef = ref<FormInstance>()
const projectForm = reactive({
  name: '',
  description: '',
  startDate: '',
  endDate: ''
})

const projectRules: FormRules = {
  name: [
    { required: true, message: '请输入项目名称', trigger: 'blur' },
    { max: 50, message: '项目名称不能超过50个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '项目描述不能超过200个字符', trigger: 'blur' }
  ]
}

const fetchProjects = async () => {
  loading.value = true
  try {
    const params = {
      keyWord: searchForm.keyWord,
      status: searchForm.status,
      beginTime: dateRange.value?.[0],
      endTime: dateRange.value?.[1],
      pageDto: {
        pageNumber: pagination.pageIndex,
        pageSize: pagination.pageSize
      }
    }
    
    const result = await getProjectList(params)
    projects.value = result.data.items
    totalCount.value = result.data.totalCount
  } catch (error) {
    ElMessage.error('获取项目列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.pageIndex = 1
  fetchProjects()
}

const handleReset = () => {
  searchForm.keyWord = ''
  searchForm.status = undefined
  dateRange.value = null
  pagination.pageIndex = 1
  fetchProjects()
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.pageIndex = 1
  fetchProjects()
}

const handleCurrentChange = (page: number) => {
  pagination.pageIndex = page
  fetchProjects()
}

const goToProject = (project: Project) => {
  router.push(`/projects/${project.id}`)
}

const handleProjectAction = async (command: string, project: Project) => {
  switch (command) {
    case 'view':
      router.push(`/projects/${project.id}`)
      break
    case 'board':
      router.push(`/projects/${project.id}/board`)
      break
    case 'members':
      router.push(`/projects/${project.id}/members`)
      break
    case 'edit':
      editingProject.value = project
      projectForm.name = project.name
      projectForm.description = project.description || ''
      projectForm.startDate = project.startDate || ''
      projectForm.endDate = project.endDate || ''
      showCreateDialog.value = true
      break
    case 'delete':
      try {
        await ElMessageBox.confirm('确定要删除这个项目吗？删除后不可恢复。', '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await deleteProject(project.id)
        ElMessage.success('删除成功')
        fetchProjects()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
      break
  }
}

const resetForm = () => {
  editingProject.value = null
  projectForm.name = ''
  projectForm.description = ''
  projectForm.startDate = ''
  projectForm.endDate = ''
  projectFormRef.value?.resetFields()
}

const handleSubmit = async () => {
  if (!projectFormRef.value) return
  
  try {
    const valid = await projectFormRef.value.validate()
    if (!valid) return
    
    submitting.value = true
    
    if (editingProject.value) {
      const updateData: UpdateProjectRequest = {
        id: editingProject.value.id,
        name: projectForm.name,
        description: projectForm.description,
        status: editingProject.value.status,
        startDate: projectForm.startDate,
        endDate: projectForm.endDate
      }
      await updateProject(updateData)
      ElMessage.success('更新成功')
    } else {
      const createData: CreateProjectRequest = {
        name: projectForm.name,
        description: projectForm.description,
        startDate: projectForm.startDate,
        endDate: projectForm.endDate
      }
      await createProject(createData)
      ElMessage.success('创建成功')
    }
    
    showCreateDialog.value = false
    fetchProjects()
  } catch (error) {
    ElMessage.error(editingProject.value ? '更新失败' : '创建失败')
  } finally {
    submitting.value = false
  }
}

const getStatusType = (status: number) => {
  return status === 1 ? 'success' : 'warning'
}

const getStatusText = (status: number) => {
  return status === 1 ? '已完成' : '进行中'
}

const formatDate = (date: string | undefined) => {
  if (!date) return '未设置'
  return dayjs(date).format('YYYY-MM-DD')
}

onMounted(() => {
  fetchProjects()
})
</script>

<style scoped lang="scss">
.projects-page {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    
    .header-left {
      h1 {
        font-size: 28px;
        color: #333;
        margin-bottom: 8px;
      }
      
      p {
        color: #666;
        font-size: 14px;
      }
    }
  }
  
  .filter-card {
    margin-bottom: 24px;
  }
  
  .project-list-card {
    .loading-container {
      padding: 40px 0;
    }
    
    .empty-state {
      padding: 60px 0;
    }
    
    .project-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
      gap: 20px;
      margin-bottom: 24px;
      
      .project-card {
        border: 1px solid #e6e6e6;
        border-radius: 8px;
        padding: 20px;
        cursor: pointer;
        transition: all 0.3s;
        
        &:hover {
          border-color: #409eff;
          box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
        }
        
        .project-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 12px;
          
          h3 {
            font-size: 18px;
            color: #333;
            margin: 0;
          }
        }
        
        .project-content {
          .description {
            color: #666;
            font-size: 14px;
            margin-bottom: 16px;
            line-height: 1.5;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
          }
          
          .project-meta {
            margin-bottom: 16px;
            
            .meta-item {
              display: flex;
              align-items: center;
              margin-bottom: 8px;
              color: #666;
              font-size: 14px;
              
              .el-icon {
                margin-right: 8px;
                color: #999;
              }
            }
          }
          
          .project-status {
            display: flex;
            justify-content: space-between;
            align-items: center;
            
            .create-time {
              color: #999;
              font-size: 12px;
            }
          }
        }
      }
    }
    
    .pagination-container {
      display: flex;
      justify-content: center;
      margin-top: 24px;
    }
  }
}

:deep(.el-dropdown-menu__item.danger) {
  color: #f56c6c;
  
  &:hover {
    background-color: #fef0f0;
    color: #f56c6c;
  }
}
</style>


